import React, { useState, CSSProperties, useEffect } from 'react';
import { Layout, Button, Popover, Space, Modal } from 'antd';
import { LeftOutlined, DownOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { SvgIcon } from '@/components/icon';
// import UserSelectModal from './UserSelectModal';
import Back from '@/components/router/Back';
import { useRouter } from '@/router/hooks';
import { useWorkBench } from '@/store/configStore';

const { Header: AntHeader } = Layout;

const navItems = [
  { key: 'answers', label: '问答', path: '' },
  { key: 'knowledge', label: '知识管理', path: '/know/datasets/list' },
];

interface User {
  id: string;
  name: string;
}

interface UserWithPermission extends User {
  permission?: string;
}

interface HeaderProps {
  isHistoryMode: boolean;
  showManage: boolean;
  onToggleHistoryMode: () => void;
  onRestoreVersion: () => void;
  onNavChange: (key: string, path: string) => void;
}

const Header: React.FC<HeaderProps> = ({
  isHistoryMode,
  showManage,
  onToggleHistoryMode,
  onRestoreVersion,
  onNavChange,
}) => {
  const navigate = useNavigate();
  const [activeKey, setActiveKey] = useState('answers');
  const [publishPopoverVisible, setPublishPopoverVisible] = useState(false);
  const [selectedVisibility, setSelectedVisibility] = useState<string | null>(null);
  const [publishButtonEnabled, setPublishButtonEnabled] = useState(false);
  const [userSelectVisible, setUserSelectVisible] = useState(false);
  const [selectedUsers, setSelectedUsers] = useState<UserWithPermission[]>([]);

  const router = useRouter();
  const workbench = useWorkBench();

  useEffect(() => {
    showManage && setActiveKey('knowledge');
  }, [showManage]);

  const handleBack = () => {
    navigate(-1);
  };

  const handleNavClick = (item: { key: string; path: string }) => {
    setActiveKey(item.key);
    onNavChange(item.key, item.path);
  };

  const handlePublish = () => {
    if (!publishButtonEnabled) return;

    if (selectedVisibility === 'private') {
      // 如果选择了部分用户可见，但还没有选择用户，则打开用户选择弹窗
      setUserSelectVisible(true);
      setPublishPopoverVisible(false);
      return;
    }

    // 点击发布按钮的逻辑
    console.log('发布应用，可见性设置为:', selectedVisibility);
    if (selectedVisibility === 'private') {
      console.log('已选择的用户:', selectedUsers);
    }

    // 发布成功后关闭弹窗
    setPublishPopoverVisible(false);
  };

  const handleVisibilityChange = (value: string) => {
    setSelectedVisibility(value);
    setPublishButtonEnabled(true);

    if (value === 'private') {
      // 不自动打开用户选择弹窗，而是等用户点击发布按钮时再打开
    }
  };

  const handleUserSelectConfirm = (users: UserWithPermission[]) => {
    setSelectedUsers(users);
    setUserSelectVisible(false);

    // 如果选择了用户，则可以继续发布流程
    if (users.length > 0) {
      // 发布应用
      console.log('发布应用，可见性设置为: 部分用户可见');
      console.log('已选择的用户:', users);
      console.log(
        '用户权限设置:',
        users.map((user) => ({
          name: user.name,
          permission: user.permission === 'full' ? '所有知识库可问答' : '部分知识库可问答',
        })),
      );
    }
  };

  const handleUserSelectCancel = () => {
    setUserSelectVisible(false);
  };

  const buttonStyle: CSSProperties = {
    borderRadius: '20px',
  };

  const getNavItemStyle = (key: string): CSSProperties => {
    if (key === activeKey) {
      return {
        background: 'linear-gradient(114.39deg, #223689 0%, #611E81 65.6%)',
        WebkitBackgroundClip: 'text',
        WebkitTextFillColor: 'transparent',
        backgroundClip: 'text',
        fontWeight: 400,
        fontSize: '20px',
        cursor: 'pointer',
        height: '64px',
        display: 'flex',
        alignItems: 'center',
        position: 'relative',
      } as CSSProperties;
    }
    return {
      color: '#666C85',
      fontWeight: 400,
      fontSize: '20px',
      cursor: 'pointer',
      height: '64px',
      display: 'flex',
      alignItems: 'center',
      position: 'relative',
    } as CSSProperties;
  };

  // 发布按钮的Popover内容
  const publishPopoverContent = (
    <div className="p-4" style={{ width: '400px' }}>
      <div className="mb-2 text-left text-sm text-[#1D2129]">当前应用未发布</div>
      <div className="mb-4 text-left text-sm text-[#86909C]">自动保存于几秒前</div>

      <div className="mb-4 mt-4 flex flex-col items-center justify-center gap-2">
        <div className="flex items-center gap-3">
          <input
            type="radio"
            id="public"
            name="visibility"
            value="public"
            className="h-4 w-4"
            checked={selectedVisibility === 'public'}
            onChange={() => handleVisibilityChange('public')}
          />
          <label htmlFor="public" className="text-sm text-[#1D2129]">
            所有人可见
          </label>
        </div>
        <div className="flex items-center gap-3">
          <input
            type="radio"
            id="private"
            name="visibility"
            value="private"
            className="h-4 w-4"
            checked={selectedVisibility === 'private'}
            onChange={() => handleVisibilityChange('private')}
          />
          <label htmlFor="private" className="text-sm text-[#1D2129]">
            部分用户可见
          </label>
        </div>
      </div>

      <Button
        type="primary"
        block
        style={{
          borderRadius: '20px',
          background: publishButtonEnabled ? '#7B67EE' : '#C4B4FF',
          border: 'none',
        }}
        className="hover:bg-[#6857D6]"
        onClick={handlePublish}
        disabled={!publishButtonEnabled}
      >
        发布
      </Button>
    </div>
  );

  return (
    <>
      <AntHeader
        style={{
          background: '#FBFCFFB2',
          height: '64px',
          lineHeight: 'normal',
          padding: '0 24px',
        }}
        className="flex items-center justify-between border-b border-[#E5E6EB]"
      >
        {/* <div className="flex items-center gap-2">
          <Button type="text" icon={<LeftOutlined />} onClick={handleBack} />
          <span className="text-[20px] font-medium text-[#1D2129]">招生助手</span>
        </div> */}
        <div className="flex items-center">
          <div className="flex">
            <Back
              title={'应用中心'}
              onClick={() => {
                router.push(workbench);
              }}
            />
          </div>
        </div>
        <div className="flex items-center gap-8">
          {navItems.map((item) => (
            <div
              key={item.key}
              style={getNavItemStyle(item.key)}
              onClick={() => handleNavClick(item)}
            >
              {item.label}
              {activeKey === item.key && (
                <div
                  style={{
                    background: 'linear-gradient(94.09deg, #768BFF 6.89%, #A073FF 98%)',
                    width: '14px',
                    height: '5px',
                    borderRadius: '20px',
                    position: 'absolute',
                    bottom: '14px',
                    left: '50%',
                    transform: 'translateX(-50%)',
                  }}
                />
              )}
            </div>
          ))}
        </div>
        <div className="flex items-center gap-2">
          {isHistoryMode ? (
            <>
              <Button
                type="primary"
                className="bg-[#7B67EE]"
                style={buttonStyle}
                onClick={onRestoreVersion}
              >
                恢复版本
              </Button>
              <Button
                className="border-[#D9D9D9] bg-[#ffffff] text-[#4E5969]"
                style={buttonStyle}
                onClick={onToggleHistoryMode}
              >
                退出版本历史
              </Button>
            </>
          ) : (
            <>
              <div className="cursor-pointer" onClick={onToggleHistoryMode} title="历史版本">
                <SvgIcon icon="ic_history" style={{ fontSize: '30px', color: '#E3E3E4' }} />
              </div>
              <Button className="bg-[#4E5969] text-white" style={buttonStyle}>
                保存
              </Button>
              <Popover
                content={publishPopoverContent}
                trigger="click"
                placement="bottomRight"
                open={publishPopoverVisible}
                onOpenChange={setPublishPopoverVisible}
                overlayClassName="publish-popover"
              >
                <Button
                  type="primary"
                  className="bg-[#4E5969] hover:bg-[#384047]"
                  style={{ ...buttonStyle, display: 'flex', alignItems: 'center' }}
                >
                  <Space>
                    发布
                    <DownOutlined style={{ fontSize: '12px' }} />
                  </Space>
                </Button>
              </Popover>
            </>
          )}
        </div>
      </AntHeader>

      {/* 用户选择弹窗 */}
      {/* <UserSelectModal
        visible={userSelectVisible}
        onCancel={handleUserSelectCancel}
        onConfirm={handleUserSelectConfirm}
      /> */}
    </>
  );
};

export default Header;
